/*
 * autostat.js
 * 实况观测
 */
;
(function(call) {
	var main = {
		baseUrl: CafeJS.CXT,
		mapId: "tjMap",
		playList: null,
		datepicker: null,
		legendpicker: null,
		router: {
			getFY4SateData: 'zhfx/satellite/queryFY4GridData',
            queryFY4GridNewTime:'/zhfx/satellite/queryFY4GridNewTime',
			getFY2SateData: 'zhfx/satellite/getSatelliteGrid',
			productcfg: "/business/common/json/product.json"
		},
		init: function() {
			this.initView();
		},
		initView: function() {
			var that = this;
			that.initDatePicker();
			$.getJSON(that.router.productcfg, function(cfg){
				that.initProductList(cfg);
			})
		},
		// 初始化产品列表
		initProductList: function(cfg) {
			var that = this
			var params = {
				container: '.product-content.sate',
				data: cfg.sate,
				eleClick: function(ele, oldEle, selected) {
					var ptype = ele.type; //当前要素的类型
					var name = ele.ele_name;

					that.clearGridLayer();

					var pro = {
						name: ptype + '_' + name,
						time: that.calcStartTime(ele),
						bussitype: 'sate',
						ele: ele,
						isGrid: true,
						isSK: true
					}
					if (selected) {
						$(".sate .product-list li.active").each(function(i, item) {
							if ($(item).data('eleid') != ele.ele_id) 
								$(item).click();
						})
						CafeJS.layerManage.removeLayer({ name: oldEle.ele_name }); // 删除上一个选中要素的图层

						// 增加产品图层
						that.addLayerManage(pro);
						that.queryEleData(ele, pro.time);
					} else {
						CafeJS.layerManage.removeLayer(pro); // 删除当前要素的图层
					}
				}
			};
			CafeJS.analysis(params);
		},
		// 初始化时间控件
		initDatePicker: function() {
			var _this =  this;
			var latestTime = new Date();
			latestTime.setMinutes(latestTime.getMinutes() - 35);
			latestTime = latestTime.format('yyyy-MM-dd hh:mm:ss');
            if($("#userInfo").data("isMatchuser")){
                latestTime = '2022-07-26 10:00:00';
            }
			this.datepicker = CafeJS.Datepicker({
				appendTo: "#datepicker-sate",
				curDate: latestTime,
				type: 3,
				timeInterval: 15,
				autoPush: true,
				call: function(val) {
					_this.queryMultiEleData();
				}
			});
			$("#datepicker-sate").show();
		},
		// 初始化图例
		initLegentpicker: function(ele, appendTo) {
			var that = this;
			var layers = that.getModels(ele);
			var layerIds = [];
			$.each(layers,function(i,m){
				layerIds.push(m.id);
			});
			CafeJS.Legentpicker({
				appendTo: appendTo,
				gisId: that.mapId,
				layerId: layerIds,
				totalWidth : 400,
				h_legend: 15,
				seq : 'decrease',
				productId: ele.color_id,
				isShowSlider : false
			});
		},
		// 初始化播放列表
		initPlayList: function(pro){
			var that = this;
			var startTime = pro.time;

			var layers = this.getModels(pro.ele);
			var interval = pro.ele.interval || 5;
			this.playList = CafeJS.Timeline3({
				appendTo : "#a-m-timeline",
				curDate : startTime,
				type : 1,
				pro: pro,
				dateOpt: {
					dateFmt : 'yyyy-MM-dd hh:mm',
					timeInterval: interval,
					customHm: []
				},
				timeInterval: interval,
				layers: layers,
				gisId : that.mapId,
				call : function(pro){
					CafeJS.layerManage.updateLayer(pro);
					var ele = pro.ele;
					that.queryEleData(ele, pro.time);
				},
				getPlayData: function(pro, timeArr){}
			});
		},
		// 查询已选择要素
		queryMultiEleData: function() {
			var that = this;
			var pro, time;
			$(".sate .product-list li.active").each(function(i, ele){
				pro = $(ele).data('pro');
				time = that.calcStartTime(pro);
				CafeJS.layerManage.updateLayerTime(time, 'sate', null, pro.ele_id);
				that.queryEleData(pro, time);
			});
		},
		// 查询要素数据
		queryEleData: function(ele, time) {
			var that = this;
			var ptype = ele.type;
			debugger
			if (ptype == 'FY2') {
				that.queryFY2GridData(ele, time);
			} else {
                that.queryFY4GridNewTimeData(ele, time)
				//that.queryFY4SateData(ele, time);
			}
		},
        queryFY4GridNewTimeData:function(ele, time){
            var that = this;
			var element = ele.ele_id;
			if (!element) return;

			if (time.indexOf(',') == -1) {
				time = new Date(time).format('yyyy-MM-dd hh:mm:ss');
			}

			var param = {
				queryTime: time,
				element: element,
				elementId: ele.ele,
				isNew: 0
			}
          $.getJSON(that.router.queryFY4GridNewTime,param,function(result){
                if(result.isSuccess && result.data){
                    CafeJS.layerManage.updateLayerTime(result.data, 'sate', null, ele.ele_id);
                    that.queryFY4SateData(ele,result.data);
                }else{
                    alert("该时间点无卫星数据");
                }
          }) 
        },
		// 获取FY4A卫星数据
		queryFY4SateData: function(ele, time){
			var that = this;
			var element = ele.ele_id;
			if (!element) return;

			if (time.indexOf(',') == -1) {
				time = new Date(time).format('yyyy-MM-dd hh:mm:ss');
			}

			var param = {
				queryTime: time,
				element: element,
				elementId: ele.ele,
				isNew: 0
			}
			loading.add();
			$.getJSON(that.router.getFY4SateData, param, function(result) {
				loading.remove();
				that.clearGridLayer();
				if (!result.isSuccess) return;
				debugger
				var data = result.data;
				var grid = data.grid;
				var data = data.data;
				if(data && data.length > 0) {
					var rangeObj = {
						nCols: grid.ny,
						nRows: grid.nx,
						ymin: grid.startLat < grid.endLat ? grid.startLat : grid.endLat,
						xmin: grid.startLon,
						ymax: grid.startLat > grid.endLat ? grid.startLat : grid.endLat,
						xmax: grid.endLon,
						xCell: grid.dx,
						yCell: grid.dy,
						noDataValue: grid.invalid,
						isCut: false,
						disInter : true
					};
					var typeObj = that.getModels(ele);;
					GIS.GridShow.showByTypes(that.mapId,typeObj, data, rangeObj, CafeJS.Legentconfig().cfg()[ele.color_id]);
				} else {
					alert("该时间点无卫星数据");
				}
			})
		},
		// 获取FY2卫星数据
		queryFY2GridData: function(ele, time) {
			var that = this;
			var ptype = ele.type;
			var element = ele.ele_id;
			if (!element) return;

			if (time.indexOf(',') == -1) {
				time = new Date(time).format('yyyy-MM-dd hh:mm:ss');
			}
			console.log('sate:' + time);

			var param = {
				queryTime: time,
				element: element,
				eleType: ptype
			}
			loading.add();
			CafeJS.ajax({
				url: that.router.getFY2SateData,
				params: param,
				type: "GET",
				success: function(e) {
					loading.remove();
					that.clearGridLayer();
					var arrayBuffer = e.response;
					if (arrayBuffer.byteLength <= 0) return;
					
					var rst = gridUtil.convertGridData3(arrayBuffer);
					if (rst == null || rst.data.length == 0) {
						alert("该时间点无卫星数据");
						return;
					}
					var grid = rst.grid;
					var rangeObj = {
						"nCols" : grid.nx,
						"nRows" : grid.ny,
						"xCell" : grid.dx,
						"yCell" : grid.dy,
						"xmax" : grid.endLon,
						"xmin" : grid.startLon,
						"ymax" : grid.startLat,
						"ymin" : grid.endLat,
						"noDataValue":grid.invalid,
						isCut: false,
						disInter : true
					};
					var typeObj = that.getModels(ele);
					GIS.GridShow.showByTypes(that.mapId,typeObj, rst.data, rangeObj, CafeJS.Legentconfig().cfg()[ele.color_id]);
				}
			})
		},
		// 增加产品图层
		addLayerManage: function(pro) {
			var that =  this;
			if (CafeJS.layerManage) {
				CafeJS.layerManage.addLayer(pro);
			} else {
				CafeJS.layerManage = CafeJS.LayerManage({
					appendTo : "#c-b-layermanage",
					mapId: that.mapId,
					proInfo: pro,
					call: function(pro) {
						CafeJS[pro.bussitype].initPlayList(pro);
					},
					more: function(pro){
						CafeJS[pro.bussitype].stationView(pro);
					},
					close: function(pro) {
						CafeJS[pro.bussitype].delLayer(pro);
					}
				})
			}
			if (pro.isGrid && pro.ele.models != "isoline") {
				that.initLegentpicker(pro.ele, '.cafe-layer-item.active');
			}
		},
		// 根据时间间隔获取开始时间
		calcStartTime: function(ele) {
			var time = new Date(this.datepicker.getVal());
			return time.format('yyyy-MM-dd hh:mm');
		},
		// 删除图层后取消要素选择
		delLayer: function(pro) {
			var eleid = pro.ele.ele_id;
			$(".sate .product-list li.active").each(function(){
				if ($(this).data('eleid') == eleid){
					$(this).click();
					return false;
				}
			})
		},
		// 清除格点GIS图层
		clearGridLayer: function() {
			var layerIds = [];
			GLMap.layerIds.forEach(function(layerId){
				if (layerId.indexOf('sate-layer') != -1) {
					layerIds.push(layerId);
				}
			})
			GIS.LayerControll.deleteLayer(this.mapId, layerIds);
		},
		// 获取要素样式
		getModels: function(ele){
			var models = [];
			$.each(ele.models.split(","),function(i,m){
				var layerId = "sate-layer-"+ m + "-" + ele.ele_id;
				models.push({
					type : m,
					visible : true,
					id : layerId
				});
			});
			return models;
		}
	};
	if (typeof call === 'function') {
		CafeJS.sate = main;
		call(main);
	}

})(function(main) {
	CafeJS.models(['datepicker', 'legentpicker', 'legentconfig', 'ajax', 'timeLine3'], function() {
		main.init();
	});
});